<template>
  <!--    查询输入框-->
  <div class="query-form">
    <el-form
        :model="queryParams"
        label-width="100px"
        @submit.prevent
        @keyup.enter="handleQuery"
    >

      <!--        航班查询-->
      <template v-if="props.queryType===QueryType.FlightQuery">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="航班出发地">
              <el-input
                  v-model="queryParams.fromCity"
                  placeholder="请输入出发地"
                  clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="航班目的地">
              <el-input
                  v-model="queryParams.arivCity"
                  placeholder="请输入目的地"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="(可选)航班号">
              <el-input
                  v-model="queryParams.flightNum"
                  placeholder="(可选)请输入航班号"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--        巴士查询-->
      <template v-else-if="props.queryType===QueryType.BusQuery">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="巴士所在地">
              <el-input
                  v-model="queryParams.busLocation"
                  placeholder="请输入巴士所在地"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--        酒店查询-->
      <template v-else-if="props.queryType===QueryType.HotelQuery">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="酒店位置">
              <el-input
                  v-model="queryParams.hotelLocation"
                  placeholder="请输入酒店位置"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="最低价格">
              <el-input-number
                  v-model="queryParams.min_price"
                  :step="100"
                  :max="queryParams.max_price"
                  :min="0"
                  size="large"
                  controls-position="right"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="最高价格">
              <el-input-number
                  v-model="queryParams.max_price"
                  :step="100"
                  :min="queryParams.min_price"
                  :max="10000"
                  size="large"
                  controls-position="right"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--        用户查询-->
      <template v-else-if="props.queryType===QueryType.CustomersQuery">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="用户名">
              <el-input
                  v-model="queryParams.customerName"
                  placeholder="请输入用户名"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--        预约查询-->
      <template v-else-if="props.queryType===QueryType.ReservationQuery">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="预约人">
              <el-input
                  v-model="queryParams.reservationOwner"
                  placeholder="请输入预约人名称"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="20">
            <el-form-item label="预约类型">
              <el-checkbox-group v-model="queryParams.reservationType">
                <el-checkbox
                    v-for="(rt) in [1,2,3]"
                    :value="rt"
                    :label="ReservationType.getTypeName(rt)"
                    name="type">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!--        查询按钮-->
      <el-form-item class="form-actions">
        <el-button type="primary" @click="handleQuery" :loading="loading">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button @click="emit('insert',true)" type="success"
                   v-show="authStore.getCustomerName==='admin' && props.queryType!==QueryType.ReservationQuery">
          <el-icon><Plus /></el-icon>
          新增数据
        </el-button>
        <el-button
          @click="handleQueryRoute"
          v-if="props.queryType===QueryType.ReservationQuery"
          type="success"
        >
          查询旅行路线
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {inject, reactive, ref, watch} from 'vue'
import {Plus, Refresh, Search} from '@element-plus/icons-vue'
import {
  type BusData,
  type CustomerData,
  type FlightData,
  type HotelData,
  type QueryParams,
  QueryType,
  type ReservationData,
  ReservationType,
  type TableData,
} from '../../../types/DataTypes.ts'
import {api} from '../../../api/Api.ts'
import {DataKey, type DataKeyType} from "../../../types/KeyTypes.ts";
import {useAuthStore} from "../../../stores/authStore.ts";
import {useRouter} from "vue-router";

// 传入参数
const props = defineProps<{
  queryType: QueryType,
}>()
const emit = defineEmits<{
  show: [boolean]
  query: [TableData]
  load: [boolean]
  insert: [boolean]
}>()

const authStore = useAuthStore();
const queryParams = reactive<QueryParams>({
  // 航班查询
  flightNum: '',
  fromCity: '',
  arivCity: '',

  // 巴士查询
  busLocation: '',

  //酒店查询
  hotelLocation: '',
  max_price: 1000,
  min_price: 0,

  // 用户
  customerName: '',

  // 预约
  reservationOwner: authStore.getCustomerName,
  reservationType: [],
})
const data = reactive<TableData>({
  busData: [],
  flightData: [],
  hotelData: [],
  customerData: [],
  reservationData: []
})
const { isNeedUpdate,updateData } = inject<DataKeyType>(DataKey) as DataKeyType;
watch(isNeedUpdate,(isNeedUpdate) => {
  if (isNeedUpdate) {
    handleQuery()
  }
})
const loading = ref(false)

// 处理重置
const handleReset = () => {
  Object.assign(queryParams,{

    // 航班查询
    flightNum: '',
    fromCity: '',
    arivCity: '',

    // 巴士查询
    busLocation: '',

    //酒店查询
    hotelLocation: '',
    min_price: 0,
    max_price: 1000,

    // 用户
    customerName: '',

    // 预约
    reservationOwner: authStore.getCustomerName,
    reservationType: [],
  })

  emit('show',false);
}

// 处理查询路线
const router = useRouter();
const handleQueryRoute = () => {
  router.push({name:'ShowRoute'})
}

// 处理查询
const handleQuery = () => {
  loading.value = true;
  emit('load',true);
  emit('show',true);

  switch (props.queryType) {
    case QueryType.FlightQuery:
      handleFlightQuery();
      break;
    case QueryType.BusQuery:
      handleBusQuery();
      break;
    case QueryType.HotelQuery:
      handleHotelQuery();
      break;
    case QueryType.CustomersQuery:
      handleCustomerQuery();
      break;
    case QueryType.ReservationQuery:
      handleReservationQuery();
      break;
  }
  updateData(data)
  emit('load',false);
  loading.value = false;
}

const noDataWarm = () => {
  ElMessage({
    message: `未查询到数据`,
    type: "warning"
  })
}

// 巴士查询
const handleBusQuery = async () => {
  let result;
  if (queryParams.busLocation===''){
    // 未输入参数,请求全部Bus信息
    result = await api.bus.getAllBuses();
  }
  else{
    // 按照参数搜索
    result = await api.bus.searchBuses(queryParams.busLocation);
  }

  if (result.success) {
    if ((result.data as BusData[]).length > 0) {
      data.busData = result.data as BusData[];
    }
    else {
      // 无查询结果
      noDataWarm();
      data.busData = []
    }
  }else {
    ElMessage.error('查询巴士失败: ' + (result.message || ''));
  }
}

// 航班查询
const handleFlightQuery = async () => {
  let result;
  if(queryParams.fromCity || queryParams.arivCity || queryParams.flightNum){
    result = await api.flight.advancedSearch(
        {
          flightNum: queryParams.flightNum,
          fromCity: queryParams.fromCity,
          arivCity: queryParams.arivCity,
        }
    )
  }
  else {
    result = await api.flight.getAllFlights();
  }

  if (result.success) {
    if ((result.data as FlightData[]).length > 0) {
      data.flightData = result.data as FlightData[];
    }
    else {
      // 无查询结果
      noDataWarm();
      data.flightData = [];
    }
  } else {
    ElMessage.error('查询航班失败: ' + (result.message || ''));
  }
}

// 酒店查询
const handleHotelQuery = async () => {
  let result;

  // 如果有搜索条件（位置或价格范围），使用高级搜索
  if (queryParams.hotelLocation || queryParams.min_price > 0 || queryParams.max_price < 1000) {
    result = await api.hotel.advancedSearch({
      location: queryParams.hotelLocation,
      minPrice: queryParams.min_price,
      maxPrice: queryParams.max_price
    });
  } else {
    // 没有搜索条件，获取所有酒店
    result = await api.hotel.getAllHotels();
  }

  if (result.success) {
    if ((result.data as HotelData[]).length > 0) {
      data.hotelData = result.data as HotelData[];
    } else {
      // 无查询结果
      noDataWarm();
      data.hotelData = [];
    }
  } else {
    ElMessage.error('查询酒店失败: ' + (result.message || ''));
  }
}

const handleCustomerQuery = async () => {
  let result;
  if (queryParams.customerName===''){
    // 未输入参数,请求全部用户信息
    result = await api.customer.getAllCustomers();
  }
  else{
    // 按照参数搜索
    result = await api.customer.searchCustomers(queryParams.customerName);
  }

  if (result.success) {
    if ((result.data as CustomerData[]).length > 0) {
      data.customerData = result.data as CustomerData[];
    }
    else {
      // 无查询结果
      noDataWarm();
      data.customerData = [];
    }
  } else {
    ElMessage.error('查询用户失败: ' + (result.message || ''));
  }
}

const handleReservationQuery = async () => {
  let result;

  if (queryParams.reservationOwner==='@all'){
    result = await api.reservation.getAllReservations();
  }
  else if (queryParams.reservationOwner===''){
    result = await api.reservation.searchReservations(
        authStore.getCustomerName,
        queryParams.reservationType)
  }
  else{
    result = await api.reservation.searchReservations(
        queryParams.reservationOwner,
        queryParams.reservationType
    )
  }

  if (result.success) {
    if ((result.data as ReservationData[]).length > 0) {
      data.reservationData = result.data as ReservationData[];
    } else {
      // 无查询结果
      noDataWarm();
      data.reservationData=[];
    }
  } else {
    ElMessage.error('查询预约失败: ' + (result.message || ''));
  }
}
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 15px;
  text-align: center;
}

.el-row {
  margin-bottom: 10px;
}
</style>